package com.ljh.trans.controller;

import com.ljh.trans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: Themberfue
 * @date: 2025/3/27 19:22
 * @description:
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    // TODO 编程式事务
    // ! 使用 IoC 的方式，手动开启事务，提交事务或者回滚事务
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/registry")
    public String registry(String username, String password) {
        // TODO 1. 开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);

        // TODO 2. 操作数据
        userService.registryUser(username, password);
        log.info("用户注册成功");

        // TODO 3. 提交事务 / 回滚事务
//        dataSourceTransactionManager.commit(transaction);
        dataSourceTransactionManager.rollback(transaction);

        return "注册成功";
    }
}
